import { message } from 'antd';
import qs from 'qs';
import { useEffect, useRef, useState } from 'react';
import dayjs, { Dayjs } from 'dayjs';

export const ranges: any = {
  今天: [dayjs(), dayjs()],
  近三天: [dayjs().subtract(2, 'day'), dayjs()],
};
export const debounce = (fn: any, delay = 500) => {
  //默认500毫秒
  let timer: any = null;
  let me: any = this;
  return function () {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(me, args);
    }, delay);
  };
};
export const throttle = (fn: any, interval: number = 300, firstTimes: boolean = true) => {
  let timer: any = null,
    firstTime: boolean = firstTimes,
    _me: any = this,
    intervalCopy: number = interval;

  return function () {
    var args: any = arguments;
    if (firstTime) {
      timer = 1;
      setTimeout(() => {
        timer = null;
      }, interval);
      intervalCopy = 0;
      fn.apply(_me, args);
      firstTime = false;
      return;
    } else {
      if (timer) {
        return;
      }
      timer = setTimeout(function () {
        intervalCopy = interval;
        clearTimeout(timer);
        timer = null;
        fn.apply(_me, args);
      }, intervalCopy);
    }
  };
};
export function getLengthArray(number = 0) {
  let linshi = [];
  for (var i = 1; i <= number; i++) {
    linshi.push(i);
  }
  return linshi;
}
export function deepClone(obj: any, hash: any = new WeakMap(), copyContructor = false) {
  hash = hash || new WeakMap();
  if (obj === null) return obj;
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(obj);
  if (typeof obj !== 'object') return obj;
  // 如果拷贝的对象是存在的，直接从WeakMap中返回即可
  if (hash.has(obj)) return hash.get(obj);
  let cloneObj: any = {};
  if (Array.isArray(obj)) {
    cloneObj = []; // 处理target是数组的情况
  }
  hash.set(obj, cloneObj);
  for (let key in obj) {
    if (copyContructor) {
      cloneObj[key] = deepClone(obj[key], hash, copyContructor);
    } else {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(key)) {
        cloneObj[key] = deepClone(obj[key], hash);
      }
    }
  }
  return cloneObj;
}
export function chinaDate(times: any, fengefu = '-') {
  if (times === null || times === undefined) {
    times = new Date();
  }
  if (typeof times === 'string') {
    times = times.replace(/-/g, '/');
  }
  fengefu = fengefu || '/';
  const time = new Date(times);
  const nian = time.getFullYear();
  const yue = ('00' + (time.getMonth() + 1)).slice(-2);
  const ri = ('00' + time.getDate()).slice(-2);
  const shi = ('00' + time.getHours()).slice(-2);
  const fen = ('00' + time.getMinutes()).slice(-2);
  const miao = ('00' + time.getSeconds()).slice(-2);
  const get0 = new Date(nian + '/' + yue + '/' + ri + ' 00:00:00').getTime();
  const get59 = new Date(nian + '/' + yue + '/' + ri + ' 23:59:59').getTime();

  return {
    fengefu,
    newDate: time,
    nian,
    yue,
    ri,
    shi,
    fen,
    miao,
    date: nian + fengefu + yue + fengefu + ri + ' ' + shi + ':' + fen + ':' + miao,
    date0: nian + fengefu + yue + fengefu + ri + ' ' + '00:00:00',
    date59: nian + fengefu + yue + fengefu + ri + ' ' + '23:59:59',
    nyr: nian + fengefu + yue + fengefu + ri,
    sfm: shi + ':' + fen + ':' + miao,
    number: time.getTime(),
    get0,
    get59,
  };
}
export function getUrlParams(urlSearch: string) {
  if (urlSearch.length === 0) {
    return {};
  } else {
    if (urlSearch.startsWith('?')) {
      return qs.parse(urlSearch.slice(1));
    } else {
      return qs.parse(urlSearch);
    }
  }
}
export const uploadChangeFun = ({
  file,
  fileList,
  setStatusF = () => {},
  formSefFiledsValue = () => {},
}: any) => {
  return new Promise((resolve: any, reject: any) => {
    // console.log("uploadChangeFun", {
    //   file,
    //   fileList,
    //   setStatusF,
    //   formSefFiledsValue,
    // });
    if (file.status === 'error') {
      reject();
      message.error(`${file.name} 上传失败`);
      return;
    }
    if (file.status === 'done') {
      resolve();
      if (file.response.success) {
        message.success(`${file.name} 上传成功`);
        setStatusF(fileList);
      } else {
        if (file.response.code === 401) {
          if (isLocal()) {
            message.error('本地cookie过期需要更换新的！');
          } else {
            window.location.href = '/apis/logout';
          }
        }
        let newFileList = fileList.filter((item: any) => {
          return item.uid !== file.uid;
        });
        if (newFileList.length === 0) {
          formSefFiledsValue();
        }
        setStatusF(newFileList);
        message.error(file.response.message);
      }
    } else {
      if (fileList.length === 0) {
        formSefFiledsValue();
      }
      setStatusF(fileList);
    }
  });
};
export const isLocal = () => {
  return ['127.0.0.1', 'localhost'].includes(window.location.hostname);
};
// 单纯a连接下载
export function aDownLoad(href: string, fileName = '') {
  const aDownload = window.document.createElement('a');
  aDownload.style.display = 'none';
  aDownload.setAttribute('downLoad', fileName);
  aDownload.setAttribute('href', href);
  document.body.appendChild(aDownload);
  aDownload.click();
  document.body.removeChild(aDownload);
}
//简单数组去重
export const setArrayOnly: any = (arrays: any[]) => {
  // eslint-disable-next-line no-undef
  return Array.from(new Set(arrays));
};
export const getParentKey = (path: any, allList: any, pathName = 'path', children = 'children') => {
  let finallyData: any = null;
  const fn = (passPath: any, passAllList: any) => {
    //console.log(passPath, passAllList);
    passAllList.forEach((item: any) => {
      if (item[pathName] === passPath) {
        finallyData = item;
      } else {
        if (item[children] && item[children].length) {
          fn(path, item[children]);
        }
      }
    });
  };
  fn(path, allList);
  return finallyData;
};
export const createParentKey = (
  passData = [],
  parentKey = '',
  id = 'key',
  children = 'children'
) => {
  passData.forEach((item: any) => {
    item.parentKey = parentKey + '' + item[id];
    if (item[children] && item[children].length > 0) {
      createParentKey(item[children], item.parentKey + ',', id, children);
    }
  });
};
